#include <stdio.h>
#include "szp_hardware_driver.h"
#include "spi_flash_fatfs_driver.h"
#include "sd_fatfs_driver.h"
#include "camera_driver.h"
#include "tinyusb_driver.h"
#include "wifi_driver.h"
#include "main_app.h"
#include "button_driver.h"
#include "ui.h"
#include "screens.h"

#include "dirent.h"
#include "my_ui_api.h"

/**
 * 文件复制函数
 * @param fileRead   要复制的文件路径
 * @param fileWrite  目标文件路径
 * @return int       1：复制成功；0：复制失败
 */
int copyFile(char *fileRead, char *fileWrite)
{
    FILE *fpRead = fopen(fileRead, "rb"); // 二进制读模式打开源文件
    if (!fpRead)
    {
        perror("Failed to open source file");
        return 0;
    }

    FILE *fpWrite = fopen(fileWrite, "wb"); // 二进制写模式创建目标文件
    if (!fpWrite)
    {
        perror("Failed to create destination file");
        fclose(fpRead);
        return 0;
    }

    // 动态分配缓冲区（建议大小 1KB~8KB）
    const int bufferLen = 4096;
    char *buffer = (char *)malloc(bufferLen);
    if (!buffer)
    {
        perror("Memory allocation failed");
        fclose(fpRead);
        fclose(fpWrite);
        return 0;
    }

    int result = 1; // 默认成功
    size_t readCount;

    // 循环读写文件内容
    while ((readCount = fread(buffer, 1, bufferLen, fpRead)) > 0)
    {
        if (fwrite(buffer, 1, readCount, fpWrite) != readCount)
        {
            perror("Write error");
            result = 0;
            break;
        }
    }

    // 检查读取是否出错
    if (ferror(fpRead))
    {
        perror("Read error");
        result = 0;
    }

    // 释放资源
    free(buffer);
    fclose(fpRead);
    fclose(fpWrite);

    return result;
}

extern "C" void app_main(void)
{
    bsp_i2c_init();   // I2C初始化
    pca9557_init();   // IO扩展芯片初始化
    bsp_lvgl_start(); // 初始化液晶屏lvgl接口
    sd_fatfs_init();
    // spi_flash_fatfs_init();

#if 0
    tinyusb_start();

    // copyFile("/sdcard/2025-04-28_16-21-55.jpg", "/spiflash/2025-04-28_16-21-55.jpg");
    // struct dirent *dir;
    // DIR *dirp;

    // /* 打开目录 */
    // dirp = opendir(SPI_FLASH_MOUNT_POINT);
    // if (NULL == dirp)
    // {
    //     perror("opendir error");
    //     exit(-1);
    // }

    // /* 循环读取目录流中的所有目录条目 */
    // while (NULL != (dir = readdir(dirp)))
    // {
    //     ESP_LOGI("main", "Found file: %s", dir->d_name);
    // }

    show_picture();
    while (1)
    {
        vTaskDelay(pdMS_TO_TICKS(1000));
    }
#endif

    lvgl_port_lock(0);
    ui_init();
    lvgl_port_unlock();
    main_task_start();
    while (1)
    {
        lvgl_port_lock(0);
        ui_tick();
        lvgl_port_unlock();
        vTaskDelay(pdMS_TO_TICKS(20));
    }
}
